/*
 * RtpPacketWriter.cpp
 *
 *  Created on: 2020年3月12日
 *      Author: chuanjiang.zh
 */

#include "RtpPacketWriter.h"
#include "RtpPackerFactory.h"
#include "CodecName.h"
#include "RtpHeader.h"

RtpPacketWriter::RtpPacketWriter()
{
}

RtpPacketWriter::~RtpPacketWriter()
{
    close();
}

bool RtpPacketWriter::open(const std::string& codec, const std::string& filepath)
{
    m_unpacker.reset(av::RtpPackerFactory::createUnPacker(av::MEDIA_TYPE_DATA, codec));
    m_unpacker->open(av::MEDIA_TYPE_DATA, av::MEDIA_CODEC_NONE);

    return m_writer.open(filepath.c_str());
}

void RtpPacketWriter::close()
{
    if (m_unpacker)
    {
        m_unpacker->close();
    }

    m_writer.close();
}

bool RtpPacketWriter::write(const uint8_t* ptr, int size)
{
    RTP_FIXED_HEADER* rtpHeader = (RTP_FIXED_HEADER*)ptr;

    if (size <= sizeof(RTP_FIXED_HEADER))
    {
		printf("invalid rtp header. size: %d\n", size);
        return false;
    }
	
    const uint8_t* data = ptr + sizeof(RTP_FIXED_HEADER);
    int  length = size - sizeof(RTP_FIXED_HEADER);

    if (rtpHeader->extension)
    {
        RTP_EXT_HEADER* extHeader = (RTP_EXT_HEADER*)data;
        int extLength = ntohs(extHeader->length);

        data += 4 + extLength * 4;
        length -= 4 + extLength * 4;

        if (length <= 0)
        {
			printf("invalid rtp with extension. size: %d\n", size);
            return false;
        }
    }

    av::RtpPacket pkt;
    pkt.data = const_cast<uint8_t*>(data);
    pkt.size = length;
    pkt.mark = rtpHeader->marker;
    pkt.seq = ntohs(rtpHeader->seq_no);
    pkt.ts = ntohl(rtpHeader->timestamp);
    pkt.pt = rtpHeader->payload;

	printf("RtpPacketWriter::write. size: %d, rtp seq: %d, pt: %d, ts: %d, mark: %d\n", pkt.size, pkt.seq, pkt.pt, pkt.ts, pkt.mark);

    av::MediaPacket packet;
    if (m_unpacker->unpack(pkt, packet))
    {
        m_writer.write(packet.data, packet.size);
    }
    return true;
}
